package session;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/sensitive")
public class SensitiveServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        //获取当次请求的session（此时可能登录，可能没有登录）
        //如果获取不到，返回null
        HttpSession session = req.getSession(false);
        if(session != null){//session不为空
            String username = (String) session.getAttribute("u");
            if(username != null){//且session设置的数据也不为空，说明已经登录
                resp.getWriter().println("用户已经登录成功，允许访问");
                return;
            }
        }
        resp.getWriter().println("用户未登录，不允许访问");
    }
}
